#include "SoftTimer.h"


//===软件定时器句柄
static Soft_Timer_Handle_Type Soft_Timer_Handle[SOFT_TIMER_MAX];

//===初始化软件定时器      参数: 必须初始化,复位结构体变量
void SoftTimer_Init(void)
{
	unsigned char i;
	for (i = 0; i < SOFT_TIMER_MAX; i++)
	{
		Soft_Timer_Handle[i].Soft_Timer_Start = 0;
		Soft_Timer_Handle[i].Soft_Timer_End = 0;
		Soft_Timer_Handle[i].delay = 0;
		Soft_Timer_Handle[i].delay_auto = 0;
		Soft_Timer_Handle[i].Soft_Time_Callback = NULL;
	}
}
//===创建一个软件定时器    参数: TimeSlice,定时时间片   Callback,回调函数
void SoftTimer_Create(Soft_Time_Delay_Type TimeSlice, void (*Callback)(void))
{
	unsigned char i;
	for (i = 0; i < SOFT_TIMER_MAX; i++)
	{
		if ((!Soft_Timer_Handle[i].Soft_Timer_Start) && (Callback != NULL))
		{
			Soft_Timer_Handle[i].delay = TimeSlice;
			Soft_Timer_Handle[i].delay_auto = TimeSlice;
			Soft_Timer_Handle[i].Soft_Time_Callback = Callback;

			Soft_Timer_Handle[i].Soft_Timer_End = 0;
			Soft_Timer_Handle[i].Soft_Timer_Start = 1;
			return;
		}
	}
}
#if 1
//===删除一个软件定时器    参数: 回调函数
void SoftTimer_Delete(void (*Callback)(void))
{
	unsigned char i;
	for (i = 0; i < SOFT_TIMER_MAX; i++)
	{
		if (Callback == Soft_Timer_Handle[i].Soft_Time_Callback)
		{
			Soft_Timer_Handle[i].Soft_Timer_Start = 0;
			Soft_Timer_Handle[i].Soft_Timer_End = 0;
			Soft_Timer_Handle[i].delay = 0;
			Soft_Timer_Handle[i].delay_auto = 0;
			Soft_Timer_Handle[i].Soft_Time_Callback = NULL;
			return;
		}
	}
}
#endif
//===软件定时器扫描        决定1个时间片的时间
void SoftTimer_Scan(void)
{
	static unsigned char i;
	for (i = 0; i < SOFT_TIMER_MAX; i++)
	{
		if (Soft_Timer_Handle[i].Soft_Timer_Start)
		{
			if (!(--Soft_Timer_Handle[i].delay))
			{
				Soft_Timer_Handle[i].delay = Soft_Timer_Handle[i].delay_auto;
				Soft_Timer_Handle[i].Soft_Timer_End = 1;
			}
		}
	}
}
//===时间到执行回调函数
void SoftTimer_PerformCallback(void)
{
	static unsigned char i;
	for (i = 0; i < SOFT_TIMER_MAX; i++)
	{
		if (Soft_Timer_Handle[i].Soft_Timer_End)
		{
			// CLEAR_WDT;
			Soft_Timer_Handle[i].Soft_Timer_End = 0;
			Soft_Timer_Handle[i].Soft_Time_Callback();		
		}
	}
}
